import { InfoCircleOutlined } from '@ant-design/icons';
import { Area } from '@ant-design/plots';
import { Card, Col, Row, Table, Tooltip } from 'antd';
import numeral from 'numeral';
import React, { useEffect, useState } from 'react';
import type { DataItem } from '../data.d';
import useStyles from '../style.style';
import NumberInfo from './NumberInfo';
import Trend from './Trend';
import { searchHive } from '@/api/masterController';

interface HiveData {
    count: number;
    tableName: string;
}

const ProportionSales = ({
    loading,
}: {
    loading: boolean;
}) => {
    const { styles } = useStyles();
    const [hiveData, setHiveData] = useState<HiveData[]>([]);

    // 计算访问比例
    const calculateAccessRatio = (currentCount: number) => {
        const totalCount = hiveData.reduce((sum, item) => sum + item.count, 0);
        return totalCount > 0 ? Math.round((currentCount / totalCount) * 100) : 0;
    };

    useEffect(() => {
        const fetchHiveData = async () => {
            try {
                const response = await searchHive();
                if (response.data && Array.isArray(response.data)) {
                    setHiveData(response.data);
                }
            } catch (error) {
                console.error('获取Hive数据失败:', error);
            }
        };

        fetchHiveData();
    }, []);

    const columns = [
        {
            title: '排名',
            dataIndex: 'index',
            key: 'index',
            width: 80,
            render: (_: any, __: any, index: number) => index + 1,
        },
        {
            title: '表名',
            dataIndex: 'tableName',
            key: 'tableName',
            render: (text: string) => <a href="/">{text}</a>,
        },
        {
            title: '访问次数',
            dataIndex: 'count',
            key: 'count',
            sorter: (a: HiveData, b: HiveData) => a.count - b.count,
        },
        {
            title: '访问比例',
            dataIndex: 'count',
            key: 'ratio',
            render: (count: number) => (
                <Trend flag={count > 0 ? 'up' : 'down'}>
                    <span style={{ marginRight: 4 }}>
                        {calculateAccessRatio(count)}%
                    </span>
                </Trend>
            ),
        },
    ];

    return (
        <Card
            loading={loading}
            bordered={false}
            title="HIVE"
            style={{
                height: '100%',
            }}
        >
            <Table<HiveData>
                rowKey={(record) => record.tableName}
                size="small"
                columns={columns}
                dataSource={hiveData}
                pagination={{
                    style: {
                        marginBottom: 0,
                    },
                    pageSize: 7,
                }}
            />
        </Card>
    );
};

export default ProportionSales;
